import FabricCanvas from '@/myFabric/FabricCanvas';
import FabricImage from '@/myFabric/FabricImage';
import FabricMark from '@/myFabric/FabricMark';
import FabricText from '@/myFabric/FabricText';
import fontManage from '@/myFabric/fontManage';
import { fabric } from 'fabric';
import { TextOptions } from 'fabric/fabric-impl';
import { get, isEmpty, set, throttle } from 'lodash';
import { autorun, toJS } from 'mobx';
import Mousetrap from 'mousetrap';
import Transition from 'three-base/Transition';
import designDataHistory from './designDataHistory';
import editorStore from './editorStore';
import textureManager from './textureManager';
import axios from 'axios';
import { message } from 'antd';
import myPhotoStore from './LeftMenu/MyPhoto/myPhotoStore';
import { GoodsData, RepeatType } from '#/type';
import utilsServer from '@/api/services/utilsServer';
import utils from '@/utils/utils';
import nameNumStore from './LeftMenu/NameNum/nameNumStore';

// 设计编辑器
class DesignEditor {
  constructor() {
    window.designEditor = this;
    // 剪贴版的数据
    let clipboards: Array<{ [key: string]: any }> = [];
    // 数据来源的部位
    let clipboardCompnent = '';

    //复制对象
    Mousetrap.bind('ctrl+c', () => {
      const activeObjs = this.fabricCanvas.getActiveObjects();
      this.fabricCanvas.discardActiveObject();
      clipboards = activeObjs
        .filter((o) => !['name', 'num'].includes(o.name || '')) // 名字号码元素不能复制
        .map((o) =>
          o.toJSON([
            'id',
            'name',
            'repeat',
            'repeatSpaceX',
            'repeatSpaceY',
            'lockMovementX',
            'lockMovementY',
            'lockRotation',
            'lockScalingX',
            'lockScalingY',
            'lockSkewingX',
            'lockSkewingY',
          ]),
        );
      clipboardCompnent = editorStore.activeComponent;
    });

    //粘贴对象
    Mousetrap.bind('ctrl+v', () => {
      if (!isEmpty(clipboards)) {
        clipboards.map((clipboard) => {
          var klass = fabric.util.getKlass(clipboard.type, '');
          clipboard.left += 10;
          clipboard.top += 10;
          if (klass) {
            klass.fromObject(clipboard, (obj: FabricImage | FabricText, error: any) => {
              if (!error) {
                obj.id = utils.uuid();
                this.fabricCanvas.add(obj);
                this.fabricCanvas.setActiveObject(obj);
                const originFabricMark = this.fabricMarkMap.get(clipboardCompnent);
                const currentFabricMark = this.fabricMarkMap.get(editorStore.activeComponent);
                if (originFabricMark && currentFabricMark) {
                  const keepScale = currentFabricMark.scaleX! / originFabricMark.scaleX!;
                  obj.scaleX! *= keepScale;
                  obj.scaleY! *= keepScale;
                }
              }
            });
          }
        });
      }
    });

    // 删除选中的对象
    Mousetrap.bind('del', () => this.delActiveObject());

    // 上移微调
    Mousetrap.bind('up', (e) => {
      this.moveActiveObject(0, -1);
    });
    // 上移粗调
    Mousetrap.bind('shift+up', (e) => {
      this.moveActiveObject(0, -5);
    });
    // 下移微调
    Mousetrap.bind('down', (e) => {
      this.moveActiveObject(0, 1);
    });
    // 下移粗调
    Mousetrap.bind('shift+down', (e) => {
      this.moveActiveObject(0, 5);
    });
    // 左移微调
    Mousetrap.bind('left', (e) => {
      this.moveActiveObject(-1, 0);
    });
    // 左移粗调
    Mousetrap.bind('shift+left', (e) => {
      this.moveActiveObject(-5, 0);
    });
    // 右移微调
    Mousetrap.bind('right', (e) => {
      this.moveActiveObject(1, 0);
    });
    // 右移微调
    Mousetrap.bind('shift+right', (e) => {
      this.moveActiveObject(5, 0);
    });
    // 最大化设计
    Mousetrap.bind('alt+r', (e) => {
      this.maxDesign();
    });
    // 铺满设计区
    Mousetrap.bind('alt+t', (e) => {
      this.coverDesigin();
    });
    // 高度最大化
    Mousetrap.bind('alt+e', (e) => {
      this.upDownCover();
    });
    // 宽度最大化
    Mousetrap.bind('alt+w', (e) => {
      this.leftRightCover();
    });
    // 水平翻转
    Mousetrap.bind('alt+,', (e) => {
      this.flipX();
    });
    // 垂直翻转
    Mousetrap.bind('alt+.', (e) => {
      this.flipY();
    });
    // 左转45°
    Mousetrap.bind('alt+f', (e) => {
      this.leftRotation45();
    });
    // 右转45°
    Mousetrap.bind('alt+g', (e) => {
      this.rightRotation45();
    });
    // 快捷设置平铺类型
    Mousetrap.bind('p', (e) => {
      this.shortcutSetRepeatType();
    });
    //放大
    Mousetrap.bind('alt+=', (e) => {
      this.amplify();
    });
    //缩小
    Mousetrap.bind('alt+-', (e) => {
      this.reduce();
    });
    //上一步
    Mousetrap.bind('ctrl+z', (e) => {
      designDataHistory.undo();
    });
    //下一步
    Mousetrap.bind('ctrl+shift+z', (e) => {
      designDataHistory.redo();
    });
    //全选
    Mousetrap.bind('ctrl+a', (e) => {
      this.selectAll();
      return false;
    });
  }

  //div容器元素
  divDom = (() => {
    const divDom = document.createElement('div');
    divDom.style.width = '1024px';
    divDom.style.height = '1024px';
    return divDom;
  })();

  // 画布
  canvas = (() => {
    const canvas = document.createElement('canvas');
    canvas.width = 1024;
    canvas.height = 1024;
    this.divDom.append(canvas);
    return canvas;
  })();

  // // 遮罩画布
  // markCanvas = (() => {
  //   const markCanvas = document.createElement('canvas');
  //   markCanvas.width = 1024;
  //   markCanvas.height = 1024;
  //   markCanvas.style.position = 'absolute';
  //   markCanvas.style.top = '0px';
  //   markCanvas.style.left = '0px';
  //   markCanvas.style.zIndex = '9';
  //   markCanvas.style.pointerEvents = 'none';
  //   markCanvas.className = 'markCanvas';
  //   this.divDom.append(markCanvas);
  //   return markCanvas;
  // })();

  //设计区域的遮罩图
  designMark = (() => {
    const designMark = new Image();
    designMark.crossOrigin = 'anonymous';
    designMark.onload = () => {
      this.render();
    }
    return designMark;
  })();

  //轮廓区域的遮罩图
  oulineMark = (() => {
    const oulineMark = new Image();
    oulineMark.crossOrigin = 'anonymous';
    oulineMark.onload = () => {
      this.render();
    }
    return oulineMark;
  })();
  oulineMarkCanvas = (() => {
    const oulineMarkCanvas = document.createElement("canvas");
    oulineMarkCanvas.width = 1024;
    oulineMarkCanvas.height = 1024;
    return oulineMarkCanvas;
  })();
  oulineMarkCanvasCtx = this.oulineMarkCanvas.getContext('2d')!;
  //设计区域的虚线图
  outlineDash = (() => {
    const outlineDash = new Image();
    outlineDash.crossOrigin = 'anonymous';
    outlineDash.onload = () => {
      this.render();
    }
    return outlineDash;
  })();

  //初始化轮廓图
  initOutline(designMarkUrl: string, oulineMarkUrl: string, outlineDashUrl: string) {
    this.designMark.src = designMarkUrl;
    this.oulineMark.src = oulineMarkUrl;
    this.outlineDash.src = outlineDashUrl;
  }

  //画布内容是否有更新
  changed = false;

  // fabric 编辑器
  fabricCanvas = (() => {
    const fabricCanvas = new FabricCanvas(this.canvas);

    //禁止右键点击事件
    fabricCanvas.on('contextmenu', (e: any) => {
      e.preventDefault();
    });

    fabricCanvas.on('before:render', (e) => {

      const { activeComponent, design_data } = editorStore;
      if (activeComponent) {
        const fabricMark = this.fabricMarkMap.get(activeComponent);
        const context = this.fabricCanvas.getContext();

        //设置编辑器布片内的布料底色
        // const lower_canvas = fabricCanvas.getElement();
        // Object.assign(lower_canvas.style, {
        //   backgroundColor: design_data.colorValue,
        // });

        //绘制编辑器布片外的白色区域
        // if (fabricMark && context) {
        //   fabricMark.clipOutLine(context, 1024, undefined, '#ffffff', 1);
        // }
      }

      // 只有执行过 before:render 事件后, 才能被视为画布有变动
      this.changed = true;

    });

    fabricCanvas.on('after:render', (e) => {
      const { activeComponent, design_data } = editorStore;
      //@ts-ignore
      // if (this._currentTransform! && activeComponent) {
      if (activeComponent && this.changed) {

        const ctx = this.fabricCanvas.getContext();

        const textCanvasCtx = textureManager.getContext(activeComponent);
        const canvasWidth = this.fabricCanvas.getWidth() * window.devicePixelRatio;
        const canvasHeight = this.fabricCanvas.getHeight() * window.devicePixelRatio;

        // 绘制设置图的遮罩
        if (this.designMark) {
          ctx.save();
          ctx.globalCompositeOperation = "destination-out";
          ctx.globalAlpha = 0.9;
          ctx.drawImage(this.designMark, 0, 0, 1024, 1024);
          ctx.restore();
        }

        // 画布有更新时, 更新对印的纹理
        textureManager.dwragToCanvas(activeComponent, this.canvas, this.designMark);

        if (this.fabricCanvas.backgroundColor) {
          this.oulineMarkCanvasCtx.globalCompositeOperation = "copy"; //覆盖替换
          this.oulineMarkCanvasCtx.fillStyle = this.fabricCanvas.backgroundColor as string;
          this.oulineMarkCanvasCtx.fillRect(0, 0, 1024, 1024);
          //衣服轮廓
          if (this.oulineMark) {
            this.oulineMarkCanvasCtx.globalCompositeOperation = "destination-out"; // 取差集
            this.oulineMarkCanvasCtx.globalAlpha = 1;
            this.oulineMarkCanvasCtx.drawImage(this.oulineMark, 0, 0, 1024, 1024);
          }
          ctx.save();
          ctx.globalCompositeOperation = "destination-over"; // 带有颜色和衣服轮廓的图案
          ctx.drawImage(this.oulineMarkCanvas, 0, 0, 1024, 1024);
          ctx.restore();
        }

        //绘制轮廓虚线图
        if (this.outlineDash) {
          ctx.save();
          ctx.globalCompositeOperation = "source-over";
          ctx.drawImage(this.outlineDash, 0, 0, 1024, 1024);
          ctx.restore();
        }

        //   const fabricMark = this.fabricMarkMap.get(activeComponent);
        //   if (fabricMark && textCanvasCtx) {
        //     fabricMark.clip(textCanvasCtx, 1024, 1);
        //   }

        //绘制背景颜色
        if (textCanvasCtx) {
          textCanvasCtx.save();
          textCanvasCtx.fillStyle =
            get(design_data, ['designData', activeComponent, 'background']) || '#ffffff';
          textCanvasCtx.globalCompositeOperation = 'destination-over';
          textCanvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
          textCanvasCtx.restore();
        }

        // //更具裁剪区域裁剪纹理canvas
        // const transparentTextCanvasCtx = textureManager.getTransparentContext(activeComponent);
        // if (fabricMark && transparentTextCanvasCtx) {
        //   fabricMark.clip(transparentTextCanvasCtx, 1024, 1);
        // }

        // //绘制编辑器的白色区域
        // const context = this.fabricCanvas.getContext();
        // if (fabricMark && context) {
        //     fabricMark.clipOutLine(context, 1024, 1, "#ffffff");
        // }

        editorStore.modifyDesignData(this.toJSON());
        const designData = toJS(editorStore.design_data.designData);
        //设置零时存储的设计数据
        designDataHistory.setStashData(designData);
      }

      this.changed = false;

      //统计对象ids
      const obects = this.fabricCanvas.getObjects();
      const ids = obects
        .map(
          (o) =>
            get(o, ['id']) +
            get(o, ['src']) +
            get(o, ['text']) +
            get(o, ['lockMovementX']) +
            get(o, ['visible']),
        )
        .join(',');
      // console.log("ids", ids);

      editorStore.setLayerIds(ids);


    });

    // 选中元素时
    fabricCanvas.on('selection:created', (e) => {
      const activeObject = get(e, ['selected', 0]) as FabricImage | FabricText;

      //名字加号码在第三步时不可选中
      if (nameNumStore.step === 3) {
        if (activeObject && ['name', 'num'].includes(activeObject.name || '')) {
          this.fabricCanvas.discardActiveObject();
          return;
        }
      }

      if (activeObject) {
        editorStore.setActiveObjectId(activeObject.id);
        editorStore.setRotation(activeObject.angle || 0);
        editorStore.setLock(!!activeObject.lockMovementX);

        switch (activeObject.type) {
          case 'image':
            editorStore.setRepeat((activeObject as FabricImage).repeat);
            editorStore.setRepeatSpaceX((activeObject as FabricImage).repeatSpaceX);
            editorStore.setRepeatSpaceY((activeObject as FabricImage).repeatSpaceY);
            editorStore.setRepeatSpacelink(
              (activeObject as FabricImage).repeatSpaceX ===
              (activeObject as FabricImage).repeatSpaceY,
            );
            editorStore.setClipSvgUrl((activeObject as FabricImage).clipSvgUrl);
            break;

          case 'i-text':
            editorStore.setFontFamily((activeObject as FabricText).fontFamily);
            editorStore.setFontSize((activeObject as FabricText).fontSize || 20);
            editorStore.setFontSpace((activeObject as FabricText).charSpacing || 0);
            editorStore.setLineHeight((activeObject as FabricText).lineHeight || 0);
            editorStore.setBendDegree((activeObject as FabricText).bendDegree || 0);
            break;

          default:
            break;
        }
      }
    });

    // 选中的元素更新
    fabricCanvas.on('selection:updated', (e) => {
      const activeObject = get(e, ['selected', 0]) as FabricImage | FabricText;

      //名字加号码在第三步时不可选中
      if (nameNumStore.step === 3) {
        if (activeObject && ['name', 'num'].includes(activeObject.name || '')) {
          this.fabricCanvas.discardActiveObject();
          return;
        }
      }

      if (activeObject) {
        editorStore.setActiveObjectId(activeObject.id);
        editorStore.setRotation(activeObject.angle || 0);
        editorStore.setLock(!!activeObject.lockMovementX);

        switch (activeObject.type) {
          case 'image':
            editorStore.setRepeat((activeObject as FabricImage).repeat);
            editorStore.setRepeatSpaceX((activeObject as FabricImage).repeatSpaceX);
            editorStore.setRepeatSpaceY((activeObject as FabricImage).repeatSpaceY);
            editorStore.setRepeatSpacelink(
              (activeObject as FabricImage).repeatSpaceX ===
              (activeObject as FabricImage).repeatSpaceY,
            );
            break;

          case 'i-text':
            editorStore.setFontFamily((activeObject as FabricText).fontFamily);
            editorStore.setFontSize((activeObject as FabricText).fontSize || 20);
            editorStore.setFontSpace((activeObject as FabricText).charSpacing || 0);
            editorStore.setLineHeight((activeObject as FabricText).lineHeight || 0);
            editorStore.setBendDegree((activeObject as FabricText).bendDegree || 0);
            break;

          default:
            break;
        }
      }
    });

    // 丢失选中的元素
    fabricCanvas.on('selection:cleared', (e) => {
      editorStore.setActiveObjectId('');
    });

    // 元素旋转时
    fabricCanvas.on('object:rotating', (e) => {
      const activeObject = get(e, ['target']) as FabricImage;
      if (activeObject) {
        activeObject.angle = Math.floor(activeObject.angle || 0);
        if (activeObject.angle > 180) {
          activeObject.angle = activeObject.angle - 360;
        }
        editorStore.setRotation(activeObject.angle || 0);
      }
    });

    // 文字调整大小时
    fabricCanvas.on('object:scaling', (e) => {
      const activeObject = get(e, ['target']) as FabricText;
      if (activeObject) {
        if (activeObject.type === 'i-text') {
          // const fontSize = activeObject.get('fontSize')!;
          // const scaleX = activeObject.get('scaleX')!;
          // const newFontSize = Math.max(20, fontSize * scaleX);
          // activeObject.set({
          //   scaleX: 1,
          //   scaleY: 1,
          //   fontSize: newFontSize,
          //   dirty: true,
          // });
          // editorStore.setFontSize(newFontSize);
        } else if (activeObject.type === 'image') {
        }
      }
    });

    return fabricCanvas;
  })();

  // 清理
  clear() {
    const objects = this.fabricCanvas.getObjects();
    for (let obj of objects) {
      this.fabricCanvas.remove(obj);
    }

    this.render();
    // const markCtx = this.markCanvas.getContext("2d")!;
    // markCtx.clearRect(0, 0, 1024, 1024);
  }

  toJSON() {
    const fabricJson = this.fabricCanvas.toJSON([
      'id',
      'name',
      'repeat',
      'repeatSpaceX',
      'repeatSpaceY',
      'lockMovementX',
      'lockMovementY',
      'lockRotation',
      'lockScalingX',
      'lockScalingY',
      'lockSkewingX',
      'lockSkewingY',
    ]);
    // 设置画布的背景
    // set(fabricJson, ['background'], '#ffffff');
    fabricJson.objects.map((o) => {
      if (o.type === 'image') {
        set(o, ['src'], (get(o, ['src']) || '').replace(/^https?:/, ''));
      }
    });

    return fabricJson;
  }

  // 设置容器
  setContainer(div: HTMLDivElement | null) {
    if (div) {
      div.style.overflow = 'hidden';
      div.innerHTML = '';
      div.append(this.divDom);
    }
  }

  //通过id 设置选中的对象
  setActiveById(id: string) {
    const objects = this.fabricCanvas.getObjects();
    const object = objects.find((o) => get(o, ['id']) === id);
    if (object) {
      this.fabricCanvas.setActiveObject(object);
    } else {
      this.fabricCanvas.discardActiveObject();
    }
    this.render();
  }

  // 删除当前选中的对象
  delActiveObject() {
    // 获取当前选中的对象数组
    var selectedObjects = this.fabricCanvas.getActiveObjects();

    // 删除选中的多个对象
    selectedObjects.forEach((object) => {
      this.fabricCanvas.remove(object);
    });

    // 清空选中状态
    this.fabricCanvas.discardActiveObject();

    this.fabricCanvas.renderAll();
  }

  //微调选中的对象
  moveActiveObject(left: number, top: number) {
    const activeObj = this.fabricCanvas.getActiveObject();
    if (activeObj) {
      activeObj.set({
        top: (activeObj.top || 0) + top,
        left: (activeObj.left || 0) + left,
      });
      this.render();
    }
  }

  // 是否有改变
  hasChange = false;
  setHasChange(hasChange: boolean) {
    this.hasChange = hasChange;
  }

  // 监听部位的改变修改部位的遮罩图 同时切换 画布数据
  dispose = autorun(
    async () => {
      const { activeComponent, goodsData } = editorStore;
      await new Promise((resolve) => requestAnimationFrame(resolve));
      const design_data = toJS(editorStore.design_data);

      // 绘制遮罩canvas
      if (activeComponent) {
        // const markCtx = this.markCanvas.getContext('2d')!;
        // markCtx.clearRect(0, 0, 1024, 1024);

        // const fabricMark = this.fabricMarkMap.get(activeComponent);
        // this.fabricCanvas.fabricMark = fabricMark;

        // if (goodsData && goodsData.fillType === 0) {
        //   //满版印按轮廓遮罩  给遮罩canvas 半透明外遮罩
        //   fabricMark && fabricMark.clipOutLine(markCtx, 1024, 1, '#f5f5f5', 0.9);
        // } else if (goodsData && goodsData.fillType === 1) {
        //   //局部印的 给遮罩canvas 绘制绘制区域线框
        //   fabricMark && fabricMark.render(markCtx);
        // }

        // // 给遮罩canvas 绘制轮廓线
        // const mask = this.maskMap.get(activeComponent);
        // mask && mask.render(markCtx);

        // 加载数据前先把轮廓渲染好
        this.render();

        // 加载设计数据
        const componentDesignData = get(design_data, ['designData', activeComponent]) || {};

        if (componentDesignData) {
          // 切换画布数据
          this.fabricCanvas.loadFromJSON(componentDesignData || {}, () => {
            // 删除没有在画布内的元素
            const objects = this.fabricCanvas.getObjects();
            objects.map((object) => {
              if (!object.isOnScreen()) {
                this.fabricCanvas.remove(object);
              }
            });
            // this.fabricCanvas.setBackgroundImage("", () => { });
            this.render();
          });
        }
      }
    },
    { delay: 10 },
  );

  //监听字体加载完成事件 并更新字体
  dispose2 = autorun(
    async () => {
      const { loadedFonts } = fontManage.store;
      await new Promise((resolve) => requestAnimationFrame(resolve));
      const objects = this.fabricCanvas.getObjects();
      objects.map((obj) => {
        if (obj.type === 'i-text' && loadedFonts.includes((obj as FabricText).fontFamily!)) {
          obj.dirty = true;
          (obj as FabricText).initDimensions();
        }
      });
      this.fabricCanvas.renderAll();
    },
    { delay: 50 },
  );

  //监听历史记录发生改变时重置数据
  dispose3 = autorun(
    async () => {
      const { currentDate } = designDataHistory.store;
      await new Promise((resolve) => requestAnimationFrame(resolve));

      this.setHasChange(true); // 数据有改变
      // 没有在记录数据时 就可以 undo redo
      if (designDataHistory.recordHistoryIng) {
        return;
      }

      const { designDataId } = designDataHistory.store;

      const designData_history = await designDataHistory.getDesignDataByIdAndDate(
        designDataId,
        currentDate,
      );

      if (designData_history) {
        const { designData: design_Data, diffKey } = designData_history;

        if (diffKey.length === 1) {
          const activeCom = (get(diffKey, [0]) || '').split('.')[0];
          if (activeCom) {
            if (currentDate) {
              editorStore.setActiveComponent(activeCom);
            }
          }
        }

        // 更新纹理对应的数据
        for (let key in design_Data) {
          editorStore.modifyDesignData(design_Data[key], key);

          if (key === editorStore.activeComponent) {
            this.fabricCanvas.loadFromJSON(design_Data[key] || {}, () => { });
          }

          // console.log('diff', name);
          await textureManager.updataTextByFabricJSON(key, design_Data[key]);
          const textCanvasCtx = textureManager.getContext(key);
          const fabricMark = this.fabricMarkMap.get(key);
          if (fabricMark && textCanvasCtx) {
            fabricMark.clip(textCanvasCtx, 1024, 1);
          }

          //绘制背景颜色
          if (textCanvasCtx) {
            textCanvasCtx.save();
            textCanvasCtx.fillStyle = get(design_Data, [key, 'background']) || '#ffffff';
            textCanvasCtx.globalCompositeOperation = 'destination-over';
            textCanvasCtx.fillRect(0, 0, 4096, 4096);
            textCanvasCtx.restore();
          }
        }
        editorStore.updataTime();
      }
    },
    { delay: 10 },
  );

  // 设置尺寸
  setSize(width: number, height: number) {
    // this.fabricCanvas.setWidth(width);
    // this.fabricCanvas.setHeight(height);
  }

  maskMap = new Map<string, fabric.Image>();

  fabricMarkMap = new Map<string, FabricMark>();

  // 初始化所有部位的遮罩对象
  async initFabricMarkMap(goodsData: GoodsData) {
    this.maskMap.clear();
    this.fabricMarkMap.clear();

    const promises: Array<Promise<void>> = [];

    const { modalSize } = goodsData;

    goodsData.component.map((c) => {
      const {
        uv_3XS,
        uv_2XS,
        uv_XS,
        uv_S,
        uv_M,
        uv_L,
        uv_XL,
        uv_2XL,
        uv_3XL,
        uv_4XL,
        uv_5XL,
        uv_6XL,
        print_area_top,
        print_area_left,
        print_area_width,
        print_area_height,
        clip_print_area_top,
        clip_print_area_left,
        clip_print_area_width,
        clip_print_area_height,
        key,
      } = c;
      let uv_url =
        uv_3XS ||
        uv_2XS ||
        uv_XS ||
        uv_S ||
        uv_M ||
        uv_L ||
        uv_XL ||
        uv_2XL ||
        uv_3XL ||
        uv_4XL ||
        uv_5XL ||
        uv_6XL;

      switch (modalSize) {
        case '3XS':
          uv_url = uv_3XS || uv_url;
          break;
        case '2XS':
          uv_url = uv_2XS || uv_url;
          break;
        case 'XS':
          uv_url = uv_XS || uv_url;
          break;
        case 'S':
          uv_url = uv_S || uv_url;
          break;
        case 'M':
          uv_url = uv_M || uv_url;
          break;
        case 'L':
          uv_url = uv_L || uv_url;
          break;
        case 'XL':
          uv_url = uv_XL || uv_url;
          break;
        case '2XL':
          uv_url = uv_2XL || uv_url;
          break;
        case '3XL':
          uv_url = uv_3XL || uv_url;
          break;
        case '4XL':
          uv_url = uv_4XL || uv_url;
          break;
        case '5XL':
          uv_url = uv_5XL || uv_url;
          break;
        case '6XL':
          uv_url = uv_6XL || uv_url;
          break;
        default:
          break;
      }

      if (uv_url) {
        const fabricMark = new FabricMark('');
        this.fabricMarkMap.set(key, fabricMark);

        const mask = new fabric.Image('');
        this.maskMap.set(key, mask);

        // 虚线打印打印区域
        fabricMark.setRectMark(
          print_area_left,
          print_area_top,
          print_area_width,
          print_area_height,
        );

        // 裁剪区域
        fabricMark.setClipRectMark(
          clip_print_area_left,
          clip_print_area_top,
          clip_print_area_width,
          clip_print_area_height,
        );

        // 轮廓图
        promises.push(
          new Promise<void>((resolve) => {
            mask.setSrc(
              uv_url,
              () => {
                const { width, height } = mask.getElement();

                // 设置裁剪区域的边长
                fabricMark.set({
                  sideLength: Math.max(width, height) * (1 / 2.8346),
                });

                const maxSide = Math.max(width, height);
                const scale = 1024 / maxSide;
                mask.set({
                  originX: 'left',
                  originY: 'top',
                  top: (1024 - height * scale) / 2,
                  left: (1024 - width * scale) / 2,
                  scaleX: scale,
                  scaleY: scale,
                });

                resolve();
              },
              { crossOrigin: 'anonymous' },
            );
          }),
        );

        // 轮廓遮罩
        promises.push(fabricMark.setvPolygonBySvg(uv_url));
      }
    });

    await Promise.all(promises);

    this.fabricMarkMap.forEach((fabricMark, name) => {
      const textureCanvas = textureManager.getCanvas(name);
      const texture = textureManager.getTexture(name);
      if (textureCanvas && texture) {
        const textureCanvasCtx = textureCanvas.getContext('2d')!;
        fabricMark.clip(textureCanvasCtx, 1024, 1);
        texture.needsUpdate = true;
      }
    });
  }

  // 添加图片
  async addImg(name: string, url: string) {
    name = name.replace(/(\'|\?|\,|\:|\.)/g, ''); // 去除名字中的特殊字符
    const img = document.createElement('img');
    img.src = url;
    img.crossOrigin = 'anonymous';
    const imgInstance = await new Promise<FabricImage>((resolve, reject) => {
      img.onload = async () => {
        // 创建一个图片对象
        const imgInstance = new FabricImage(img);

        // 计算打印区域
        const { left, top, width, height } = this.get_print_area();
        const scaleX = width / (imgInstance.width || 10);
        const scaleY = height / (imgInstance.height || 10);

        imgInstance.set({
          angle: 0,
          name: name,
          id: utils.uuid(),
          scaleX: Math.min(scaleX, scaleY),
          scaleY: Math.min(scaleX, scaleY),
          left: left + width / 2,
          top: top + height / 2,
        });

        const objs = this.fabricCanvas.getObjects();
        if (objs.length) {
          objs.map((obj) => {
            if (obj.left === imgInstance.left) {
              imgInstance.left! += 10;
            }
            if (obj.top === imgInstance.top) {
              imgInstance.top! += 10;
            }
          });
        }

        this.fabricCanvas.add(imgInstance);
        this.fabricCanvas.setActiveObject(imgInstance);
        this.render();
        resolve(imgInstance);
      };

    });
    return imgInstance;
  }

  //添加文本
  addText(text: string, options?: TextOptions) {
    const fabricText = new FabricText(text, options);
    fabricText.set({
      fontSize: 100,
      id: utils.uuid(),
      left: 512,
      top: 512,
    });
    fabricText._updatePath();
    this.fabricCanvas.add(fabricText);
    return fabricText;
  }

  // 动画对象
  transition = (() => {
    const transition = new Transition({ angle: 0, scaleX: 1, scaleY: 1, left: 512, top: 512 });
    transition.setDuration(150);
    transition.onChange(({ angle, left, top, scaleX, scaleY }) => {
      const activeObject = this.fabricCanvas.getActiveObject();
      if (activeObject) {
        if (angle > 180) {
          angle -= 360;
        } else if (angle < -180) {
          angle += 360;
        }

        activeObject.angle = Math.floor(angle);
        editorStore.setRotation(Math.floor(angle));
        activeObject.left = left;
        activeObject.top = top;
        activeObject.scaleX = scaleX;
        activeObject.scaleY = scaleY;
        this.render();
      }
    });
    return transition;
  })();

  // 重置动画对象的参数;
  resetTransition() {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      this.transition.reset({
        angle: activeObject.angle || 0,
        left: activeObject.left || 0,
        top: activeObject.top || 0,
        scaleX: activeObject.scaleX || 1,
        scaleY: activeObject.scaleY || 1,
      });
    }
  }

  // 全选
  selectAll() {
    this.fabricCanvas.discardActiveObject();
    const objects = this.fabricCanvas.getObjects();
    const aGroup = new fabric.ActiveSelection(objects.reverse(), {
      canvas: this.fabricCanvas,
    });
    const center = aGroup.getCenterPoint();
    aGroup.originX = 'center';
    aGroup.originY = 'center';
    aGroup.left = center.x;
    aGroup.top = center.y;
    this.fabricCanvas.setActiveObject(aGroup);
    designEditor.fabricCanvas.renderAll();
  }

  //获取计算好的打印区域的宽高和位置
  get_print_area() {
    const { activeComponent, goodsData } = editorStore;
    const fabricMark = this.fabricMarkMap.get(activeComponent);
    if (goodsData && fabricMark) {
      const component = goodsData.component.find((c: any) => c.key === activeComponent);
      if (component) {
        const { print_area_height, print_area_left, print_area_top, print_area_width } = component;
        return {
          left: (Math.min(print_area_left, fabricMark.sideLength) * 1024) / fabricMark.sideLength,
          top: (Math.min(print_area_top, fabricMark.sideLength) * 1024) / fabricMark.sideLength,
          width: (Math.min(print_area_width, fabricMark.sideLength) * 1024) / fabricMark.sideLength,
          height:
            (Math.min(print_area_height, fabricMark.sideLength) * 1024) / fabricMark.sideLength,
        };
      }
    }
    return { left: 0, top: 0, width: 0, height: 0 };
  }

  //  最大化设计
  maxDesign() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      // 计算打印区域
      const { left, top, width, height } = this.get_print_area();
      const scaleX = width / (activeObject.width || 10);
      const scaleY = height / (activeObject.height || 10);
      this.transition.set({
        angle: 0,
        scaleX: Math.max(scaleX, scaleY),
        scaleY: Math.max(scaleX, scaleY),
        left: left + width / 2,
        top: top + height / 2,
      });
    }
  }

  //铺满设计
  coverDesigin() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      // 计算打印区域
      const { left, top, width, height } = this.get_print_area();
      const scaleX = width / (activeObject.width || 10);
      const scaleY = height / (activeObject.height || 10);
      // 设置缩放值
      this.transition.set({
        angle: 0,
        scaleX,
        scaleY,
        left: left + width / 2,
        top: top + height / 2,
      });
    }
  }

  // 上下铺满
  upDownCover() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      // 计算打印区域
      const { left, top, width, height } = this.get_print_area();
      // 计算缩放值
      const scale = height / (activeObject.height || 10);
      // 设置缩放值
      this.transition.set({
        angle: 0,
        scaleX: scale,
        scaleY: scale,
        left: left + width / 2,
        top: top + height / 2,
      });
    }
  }

  //左右铺满
  leftRightCover() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      // 计算打印区域
      const { left, top, width, height } = this.get_print_area();
      // 计算缩放值
      const scale = width / (activeObject.width || 10);
      // 设置缩放值
      this.transition.set({
        angle: 0,
        scaleX: scale,
        scaleY: scale,
        left: left + width / 2,
        top: top + height / 2,
      });
    }
  }

  //放大
  amplify() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      // 设置缩放值
      this.transition.set({
        scaleX: activeObject.scaleX! * 1.1,
        scaleY: activeObject.scaleY! * 1.1,
      });
    }
  }

  // 锁小
  reduce() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      // 设置缩放值
      this.transition.set({
        scaleX: activeObject.scaleX! * 0.9,
        scaleY: activeObject.scaleY! * 0.9,
      });
    }
  }

  //  左对齐
  leftAlign() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      const { left, top, width, height } = this.get_print_area();
      const scaleWidth = activeObject.getScaledWidth();
      // 设置缩放值
      this.transition.set({ left: left + scaleWidth / 2 });
    }
  }

  // 水平对齐
  horizontalAlign() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      const { left, top, width, height } = this.get_print_area();
      // 设置缩放值
      this.transition.set({ left: left + (width / 2) });
    }
  }

  // 右对齐
  rightAlign() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      const { left, top, width, height } = this.get_print_area();
      const scaleWidth = activeObject.getScaledWidth();
      // 设置缩放值
      this.transition.set({ left: left + width - scaleWidth / 2 });
    }
  }

  // 顶对齐
  topAlign() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      const { left, top, width, height } = this.get_print_area();
      const scaleHeight = activeObject.getScaledHeight();
      this.transition.set({ top: top + scaleHeight / 2 });
    }
  }

  // 垂直对齐
  verticalAlign() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      const { left, top, width, height } = this.get_print_area();
      this.transition.set({ top: top + height / 2 });
    }
  }

  // 下对齐
  bottomAlign() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      const { left, top, width, height } = this.get_print_area();
      const scaleHeight = activeObject.getScaledHeight();
      this.transition.set({ top: top + height - scaleHeight / 2 });
    }
  }

  // 复制
  copy() {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      activeObject.clone(
        (newObj: fabric.Object) => {
          newObj.left! += 20;
          newObj.top! += 20;
          this.fabricCanvas.add(newObj);
          this.fabricCanvas.setActiveObject(newObj);
        },
        [
          'id',
          'name',
          'repeat',
          'repeatSpaceX',
          'repeatSpaceY',
          'lockMovementX',
          'lockMovementY',
          'lockRotation',
          'lockScalingX',
          'lockScalingY',
          'lockSkewingX',
          'lockSkewingY',
        ],
      );
    }
  }

  //左右翻转
  flipX() {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      activeObject.flipX = !activeObject.flipX;
      this.render();
    }
  }

  // 上下翻转
  flipY() {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      activeObject.flipY = !activeObject.flipY;
      this.render();
    }
  }

  // 左转45°
  leftRotation45() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      // 设置缩放值
      this.transition.set({ angle: (activeObject.angle || 0) - 45 });
    }
  }

  // 右转45°
  rightRotation45() {
    this.resetTransition();
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      // 设置缩放值
      this.transition.set({ angle: (activeObject.angle || 0) + 45 });
    }
  }

  // 设置旋转角度
  setRotation(angle: number, duration: number = 300) {
    const activeObject = this.fabricCanvas.getActiveObject();

    if (activeObject) {
      this.transition.reset({
        angle: activeObject.angle || 0,
        left: activeObject.left || 0,
        top: activeObject.top || 0,
        scaleX: activeObject.scaleX || 1,
        scaleY: activeObject.scaleY || 1,
      });

      // 设置缩放值
      this.transition.setDuration(duration).set({ angle });
    }
  }

  // 通过id获取对象
  getObjectById(id: string) {
    const objects = this.fabricCanvas.getObjects();
    const object = objects.find((o) => get(o, ['id']) === id);
    return object;
  }

  //设置锁定状态
  setLockState(lock: boolean) {
    editorStore.setLock(lock);
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      activeObject.set({
        lockMovementX: lock,
        lockMovementY: lock,
        lockRotation: lock,
        lockScalingX: lock,
        lockScalingY: lock,
        lockSkewingX: lock,
        lockSkewingY: lock,
      });

      if (activeObject instanceof FabricText) {
        activeObject.set({
          editable: !lock,
        });
      }

      this.fabricCanvas.renderAll();
    }
  }

  //获取锁定状态通过状态
  getLock(id: string) {
    const object = this.getObjectById(id);
    if (object) {
      return !!object.lockMovementX;
    }
    return false;
  }

  //设置锁定状态通过状态
  setLockById(id: string, lock: boolean) {
    const object = this.getObjectById(id);
    if (object) {
      // 设置当前选中对象的锁定状态
      if (editorStore.activeObjectId === id) {
        editorStore.setLock(lock);
      }

      object.set({
        lockMovementX: lock,
        lockMovementY: lock,
        lockRotation: lock,
        lockScalingX: lock,
        lockScalingY: lock,
        lockSkewingX: lock,
        lockSkewingY: lock,
      });

      if (object instanceof FabricText) {
        object.set({
          editable: !lock,
        });
      }

      this.render();
    }
  }

  // 获取可见状态
  getVisibleById(id: string) {
    const object = this.getObjectById(id);
    if (object) {
      return object.visible;
    }
    return false;
  }

  //设置可见状态
  setVisibleById(id: string, visible: boolean) {
    const object = this.getObjectById(id);
    if (object) {
      object.visible = visible;
      this.render();
    }
  }

  //快捷设置平铺方式
  shortcutSetRepeatType() {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'image') {
      switch ((activeObject as FabricImage).repeat) {
        case 'no_repeat':
          this.setRepeatType('base_repeat');
          break;

        case 'base_repeat':
          this.setRepeatType('mirror_repeat');
          break;

        case 'mirror_repeat':
          this.setRepeatType('horizontal_repeat');
          break;

        case 'horizontal_repeat':
          this.setRepeatType('vertical_repeat');
          break;

        case 'vertical_repeat':
          this.setRepeatType('no_repeat');
          editorStore.setShowRepeatSpaceContorl(false);
          break;

        default:
          break;
      }
    }
  }

  //设置平铺类型
  setRepeatType(repeatType: RepeatType) {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'image') {
      if ((activeObject as FabricImage).repeat !== repeatType) {
        (activeObject as FabricImage).repeat = repeatType;
        editorStore.setShowRepeatSpaceContorl(true);
      } else {
        (activeObject as FabricImage).repeat = 'no_repeat';
        editorStore.setShowRepeatSpaceContorl(false);
      }
      editorStore.setRepeat((activeObject as FabricImage).repeat);
      this.render();
    }
  }

  //设置平铺的横向间距
  setRepeatSpaceX(repeatSpaceX: number = 0) {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'image') {
      (activeObject as FabricImage).repeatSpaceX = repeatSpaceX;
      editorStore.setRepeatSpaceX(repeatSpaceX);
      this.render();
    }
  }

  //设置纵向平铺的方法
  setRepeatSpaceY(repeatSpaceY: number = 0) {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'image') {
      (activeObject as FabricImage).repeatSpaceY = repeatSpaceY;
      editorStore.setRepeatSpaceY(repeatSpaceY);
      this.render();
    }
  }

  // 设置选中对象的颜色
  setActiveFill(fill: string) {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject) {
      activeObject.set({ fill });
      this.render();
      if (activeObject.name === 'name') {
        editorStore.setNameColor(fill);
      } else if (activeObject.name === 'num') {
        editorStore.setNumColor(fill);
      }
    }
  }

  //设置字体
  setFontFontFamily(fontFamily: string) {
    fontManage.loadFont([fontFamily]);
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'i-text') {
      (activeObject as FabricText).set("fontFamily", fontFamily);
      this.render();
      if (activeObject.name === 'name') {
        editorStore.setNameFontFamily(fontFamily);
      } else if (activeObject.name === 'num') {
        editorStore.setNumFontFamily(fontFamily);
      }
    }
  }

  //设置字体大小
  setFontSize(fontSize: number) {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'i-text') {
      (activeObject as FabricText).set("fontSize", fontSize);
      this.render();
    }
  }

  //设置字体间距
  setFontSpace(charSpacing: number) {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'i-text') {
      (activeObject as FabricText).set("charSpacing", charSpacing);
      this.render();
    }
  }

  //设置字体的行高
  setLineHeight(lineHeight: number) {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'i-text') {
      (activeObject as FabricText).set("lineHeight", lineHeight);
      this.render();
    }
  }

  //设置字体字重
  setFontWeight(fontWeight: string = 'normal') {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'i-text') {
      (activeObject as FabricText).set("fontWeight", fontWeight);
      this.render();
    }
  }

  //设置字体的对齐方式
  setTextAlign(textAlign: string) {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'i-text') {
      (activeObject as FabricText).set("textAlign", textAlign);
      this.render();
    }
  }

  //设置文字的描边颜色
  setStrokeColor(strokeColor: string) {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'i-text') {
      (activeObject as FabricText).set("stroke", strokeColor);
      this.render();
    }
  }

  //设置当前对象的对齐方式
  setObjectAilgn(
    ailgnType:
      | 'leftTop'
      | 'top'
      | 'rightTop'
      | 'left'
      | 'center'
      | 'right'
      | 'leftBottom'
      | 'bottom'
      | 'rightbottom',
  ) {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (!activeObject) {
      return;
    }

    // 计算打印区域
    const { left, top, width, height } = this.get_print_area();
    //计算对象的尺寸
    const objectWightHalf = activeObject.getScaledWidth() / 2;
    const objectHeightHalf = activeObject.getScaledHeight() / 2;
    const widthHalf = width / 2;
    const heightHalf = height / 2;

    this.resetTransition();

    switch (ailgnType) {
      case 'leftTop':
        this.transition.set({ left: objectWightHalf + left, top: objectHeightHalf + top });
        break;
      case 'top':
        this.transition.set({ left: widthHalf + left, top: objectHeightHalf + top });
        break;
      case 'rightTop':
        this.transition.set({ left: width - objectWightHalf + left, top: objectHeightHalf + top });
        break;
      case 'left':
        this.transition.set({ left: objectWightHalf + left, top: heightHalf + top });
        break;
      case 'center':
        this.transition.set({ left: widthHalf + left, top: heightHalf + top });
        break;
      case 'right':
        this.transition.set({ left: width - objectWightHalf + left, top: heightHalf + top });
        break;
      case 'leftBottom':
        this.transition.set({ left: objectWightHalf + left, top: height - objectHeightHalf + top });
        break;
      case 'bottom':
        this.transition.set({ left: widthHalf + left, top: height - objectHeightHalf + top });
        break;
      case 'rightbottom':
        this.transition.set({
          left: width - objectWightHalf + left,
          top: height - objectHeightHalf + top,
        });
        break;
    }

    // this.render();
  }

  //抠人像
  async matting() {

    const canUse = await editorStore.updateAiUseCount("kouTu").catch(() => false);
    if (!canUse) {
      message.error('抠图使用次数已达上限');
      return;
    }

    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'image') {
      return new Promise<boolean>(async (resolve, reject) => {
        let url = (activeObject as FabricImage).getSrc();
        url = utils.ossSuffix(url, 2500);

        const response = await axios({
          method: 'get',
          url: url,
          responseType: 'blob',
        });

        // const resizedImage = await createImageBitmap(imgUrl, 0, 0, undefined, undefined, {
        //     resizeWidth: maxWidth,
        //     resizeHeight: maxHeight,
        //     resizeQuality: 'high' // 可选，某些浏览器可能不支持
        // });

        // 创建一个FileReader对象
        const reader = new FileReader();

        // 当FileReader读取完成时，获取结果
        reader.onloadend = async () => {
          // 读取结果会存储在result属性中，格式为DataURL（即Base64编码的字符串）
          const base64 = reader.result;

          var data: any = {
            photo: base64,
            type: 'jpg',
            face_required: '0', // 可选，整形，检测是否必须带有人脸才进行抠图处理，0为检测，1为不检测，默认为0，设置这个参数后，可能导致人体背影无法抠图
            is_crop_content: '0', // 可选，整形，是否值返回人像区域，其余透明区域，都被裁剪掉，0为否，1为是，默认为0
          };
          data = JSON.stringify(data);
          const CryptoJS = await import('crypto-js');
          var md5_data = CryptoJS.MD5(CryptoJS.enc.Utf8.parse(data));
          var content_md5 = CryptoJS.enc.Base64.stringify(md5_data);
          axios
            .post('https://matting.market.alicloudapi.com/segment/matting', data, {
              headers: {
                Accept: 'application/json; charset=utf-8',
                Authorization: 'APPCODE ' + '8d5e78f1c0f44a1288d22b2374957f2a',
                'Content-Type': 'application/json; charset=UTF-8',
                'Content-MD5': content_md5,
              },
            })
            .then(async (res) => {
              const originUrl = get(res, ['data', 'data', 'result']);
              if (originUrl) {
                const file = await utilsServer.url_to_file(originUrl);
                const uploadUrl = await utilsServer.uploadOss(file);
                // 处理完成的图片在我的上传里保存一份
                myPhotoStore.uploadUrl(uploadUrl);

                const ossUrl = utils.ossSuffix(uploadUrl, 400);
                const originWidth = activeObject.getScaledWidth();
                const originHeight = activeObject.getScaledHeight();
                (activeObject as FabricImage).setSrc(
                  ossUrl,
                  () => {
                    const { width, height } = activeObject;
                    const scale = Math.min(originWidth / width!, originHeight / height!);
                    activeObject.set({
                      scaleX: scale,
                      scaleY: scale,
                    });
                    this.render();
                  },
                  { crossOrigin: 'anonymous' },
                );

                resolve(true);
              }
            })
            .catch((err) => {
              message.error('抠图失败');
              resolve(true);
            });
        };

        // 将Blob对象转换为DataURL
        reader.readAsDataURL(response.data);
      });
    }
  }

  //人像动漫化
  async anime() {

    const canUse = await editorStore.updateAiUseCount("kouTu").catch(() => false);
    if (!canUse) {
      message.error('动漫化使用次数已达上限');
      return;
    }

    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'image') {
      return new Promise<boolean>(async (resolve, reject) => {
        let url = (activeObject as FabricImage).getSrc();
        url = utils.ossSuffix(url, 1000);
        const formData = new FormData();
        formData.append('url', `https:${url}`);

        axios
          .post('https://jmrxdmsc.market.alicloudapi.com/rxdmsc/selfie/anime', formData, {
            headers: {
              Accept: 'application/json; charset=utf-8',
              Authorization: 'APPCODE ' + '8d5e78f1c0f44a1288d22b2374957f2a',
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
          })
          .then(async (res) => {
            const originUrl = get(res, ['data', 'data', 'url']);
            if (originUrl) {
              const file = await utilsServer.url_to_file(originUrl);
              const uploadUrl = await utilsServer.uploadOss(file);

              // 处理完成的图片在我的上传里保存一份
              myPhotoStore.uploadUrl(uploadUrl);

              const ossUrl = utils.ossSuffix(uploadUrl, 400);
              const originWidth = activeObject.getScaledWidth();
              const originHeight = activeObject.getScaledHeight();
              (activeObject as FabricImage).setSrc(
                ossUrl,
                () => {
                  const { width, height } = activeObject;
                  const scale = Math.min(originWidth / width!, originHeight / height!);
                  activeObject.set({
                    scaleX: scale,
                    scaleY: scale,
                  });
                  this.render();
                },
                { crossOrigin: 'anonymous' },
              );

              resolve(true);
            }
          })
          .catch((err) => {
            const msg = get(err, ['response', 'data', 'msg']);
            if (msg) {
              message.error(msg);
            }
            resolve(false);
          });
      });
    }
  }

  //设置文字描边的宽度
  setStrokeWidth = throttle((strokeWidth: number) => {
    const activeObject = this.fabricCanvas.getActiveObject();
    if (activeObject && activeObject.type === 'i-text') {
      (activeObject as FabricText).set("strokeWidth", strokeWidth);
      this.render();
    }
  }, 50);

  //设置颜色
  setColor = throttle(
    async (color: string, colorValue: `#${string}`, components: Array<string>) => {
      editorStore.design_data.color = color;
      editorStore.design_data.colorValue = colorValue;
      const design_data = toJS(editorStore.design_data.designData);
      for (let name of components) {
        if (!isEmpty(design_data[name])) {
          design_data[name].background = colorValue;
          editorStore.modifyDesignData(design_data[name], name);
          await textureManager.updataTextByFabricJSON(name, design_data[name]);
          const textCanvasCtx = textureManager.getContext(name);
          const fabricMark = designEditor.fabricMarkMap.get(name);
          if (fabricMark && textCanvasCtx) {
            fabricMark.clip(textCanvasCtx, 1024, 1);
          }

          //绘制背景颜色
          if (textCanvasCtx) {
            textCanvasCtx.save();
            textCanvasCtx.fillStyle = colorValue;
            textCanvasCtx.globalCompositeOperation = 'destination-over';
            textCanvasCtx.fillRect(0, 0, 1024, 1024);
            textCanvasCtx.restore();
          }
        }
      }
      editorStore.updataTime();
      this.fabricCanvas.backgroundColor = colorValue;
      designEditor.render();
      designEditor.setHasChange(true);
    },
    50,
  );

  // 渲染画布
  async render() {
    this.fabricCanvas.requestRenderAll();
  }
}

const designEditor = new DesignEditor();

//当选中部位发生变化时就切换遮罩图
const dispose = autorun(() => {
  const { activeComponent, goodsData } = editorStore;
  if (goodsData) {
    const com = goodsData.component.find(c => c.key === activeComponent);
    if (com) {
      const { designMark, oulineMark, outlineDash } = com;
      designEditor.initOutline(designMark, oulineMark, outlineDash);

    }

  }
}, { delay: 30 });

export default designEditor;
